'use strict';
const ora = require('ora')
const childProcess = require('child_process');

function isObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]'
}

function spinnerStart(options) {
    const spinner = ora(options)
    spinner.start()
    return spinner
}

async function sleep(time=2000) {
    await new Promise(resolve => {
        setTimeout(resolve, time)
    })
}

function exec(command, args, options) {
    const win32 = process.platform === 'win32'
    const cmd = win32 ? 'cmd' : command
    const cmdArgs = win32 ? ['/c'].concat(command, args) : args;

    return childProcess.spawn(cmd, cmdArgs, options || [])
}

function execAsync(command, args, options) {
    return new Promise((resolve, reject) => {
        const p = exec(command, args, options)
        p.on('error', e => {
            reject(e)
        })
        p.on('exit', c => {
            resolve(c)
        })
    })
}

module.exports = {
    isObject,
    spinnerStart,
    sleep,
    exec,
    execAsync
};
